package main

import (
	"context"
	"encoding/json"
	"fmt"
	"os"

	"github.com/tendermint/tendermint/rpc/client/http"
	"github.com/tendermint/tendermint/types"
)

func main() {
	chainids := []string{"b1", "i1", "i2"}
	cli, err := http.New("http://127.0.0.1:26657", "/websocket")
	if err != nil {
		panic(err)
	}
	abciQueryRes, err := cli.ABCIQuery(context.TODO(), "", nil)
	height := abciQueryRes.Response.Height
	var i int64 = 3
	var count int64 = 0
	for ; i < height; i++ {

		blockRes, err := cli.Block(context.TODO(), &i)
		if err != nil {
			panic(err)
		}

		// 获取区块的数据部分（block.Block.Data）

		databp := blockRes.Block.Txs

		// 存储区块数据到文件
		cid := chainids[count%3]
		Write(databp, count/3, cid)
		count++
	}
}

func Write(txs types.Txs, height int64, chain_id string) {
	filepath := "/home/llm/tdmt12/full/tendermint_subject2/my_app/blockdata"
	fileName := fmt.Sprintf("%s/block_%d_%s.dat", filepath, height, chain_id)

	file, err := os.OpenFile(fileName, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0777)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	// for _, tx := range txs {
	// 	_, err = file.Write(tx)
	// 	if err != nil {
	// 		panic(err)
	// 	}

	// 	file.Write([]byte("\n"))
	// }
	jsonData, err := json.MarshalIndent(txs, "", "  ")
	if err != nil {
		return
	}

	err = os.WriteFile(fileName, jsonData, 0644)
	if err != nil {
		return
	}
}
